package server;

import server.mapper.Context;
import server.mapper.Host;
import server.mapper.Mapper;
import server.mapper.Wrapper;

import java.io.InputStream;
import java.net.Socket;

public class HomeworkRequestProcessor extends Thread {

    private Socket socket;
    private Mapper mapper;

    public HomeworkRequestProcessor(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            int localPort = socket.getLocalPort();
            String[] path = request.getUrl().trim().split("/");
            if (path.length < 2) {
                response.outputHtml(request.getUrl(), false);
                return;
            }

            Host host = mapper.get(String.valueOf(localPort));
            String ctxPath = path[1];
            Context context = host.getUrlContextMap().get(ctxPath);


            String url = request.getUrl().trim().substring(path[1].length() + 1);
            if (context == null || context.getWrapperMap() == null || context.getWrapperMap().get(url) == null) {
                // 静态资源处理
                if (context == null) {
                    response.outputHtml(url, false);
                } else {
                    String absolutePath = context.getPath() + url;
                    absolutePath = absolutePath.replaceAll("\\\\", "/");
                    response.outputHtml(absolutePath, true);
                }
            } else {
                // 动态资源servlet请求
                Wrapper wrapper = context.getWrapperMap().get(url);
                wrapper.getServlet().service(request, response);
            }

            socket.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
